<?php

namespace app\api\controller\user;

use app\api\constant\StatusConst;
use app\api\model\UserAddress;
use app\api\services\user\AddressServices;
use app\common\controller\Api;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\Request;

class Address extends Api
{
    protected $noNeedLogin = ['edit'];
    protected $noNeedRight = '*';

    /**
     * 修改地址失败
     * @param Request $request
     * @return void
     * @throws Exception
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function edit(Request $request)
    {
        $addressInfo = $request->postMore([
            ['address', []],
            ['is_default', false],
            ['real_name', ''],
            ['post_code', ''],
            ['phone', ''],
            ['detail', ''],
            [['id', 'd'], 0],
            [['type', 'd'], 0]
        ]);
//        $addressInfo = [
//            'address' => [
//                'city' => '北京市',
//                'city_id' => 2,
//                'district' => '八嘎',
//                'province' => '北京市'
//            ],
//            'detail' => '123',
//            'id' => 1,
//            'is_default' => 0,
//            'phone' => '13285471922',
//            'real_name' => 'test',
//        ];

        if (!isset($addressInfo['address']['province']) || !$addressInfo['address']['province'] || $addressInfo['address']['province'] == '省') $this->error('参数不合法');
        if (!isset($addressInfo['address']['city']) || !$addressInfo['address']['city'] || $addressInfo['address']['city'] == '市') $this->error('参数不合法');
        if (!isset($addressInfo['address']['district']) || !$addressInfo['address']['district'] || $addressInfo['address']['district'] == '区') $this->error('参数不合法');
        if (!isset($addressInfo['address']['city_id']) && $addressInfo['type'] == 0) $this->error('参数不合法');
        $userid = $this->auth->id;

        $res = AddressServices::getInstance()->editAddress($userid, $addressInfo);
        if ($res) $this->success();
        $this->error("修改失败");
    }

    /**
     * 收货地址列表
     * @return void
     * @throws DbException
     */
    public function list()
    {
        $userid = $this->auth->id;
        $this->paginate(AddressServices::getInstance()->getUserAddressList($userid));
    }

    /**
     * 删除地址
     * @return void
     */
    public function delete()
    {
        $id = input('id');
        if (empty($id)) {
            $this->error("请选择要删除的地址");
        }
        try {
            UserAddress::update([
                'is_del' => StatusConst::NORMAL
            ], ['id' => $id]);
        } catch (Exception $e) {
            $this->error("删除失败");
        }
        $this->success();

    }
}